import numpy as np
import pandas as pd
import datetime

def get_start_end_times_corrected(row):
    date = row['parsed_date'].split('/')
    date = [i if len(i) != 1 else '0' + i for i in date]
    date = '20' + date[2] + '-' + date[0] + '-' + date[1]

    if row['time_start'] is np.nan:
        return np.nan, np.nan
    elif '/' in row['time_start']:
        start_time = datetime.datetime.strptime(row['time_start'], '%m/%d/%y %H:%M')
    else:
        start_time = datetime.datetime.strptime(date + ' ' + row['time_start'], '%Y-%m-%d %H:%M')

    if '/' in row['time_end']:
        end_time = datetime.datetime.strptime(row['time_end'], '%m/%d/%y %H:%M')
    else:
        end_time = datetime.datetime.strptime(date + ' ' + row['time_end'], '%Y-%m-%d %H:%M')
    return start_time, end_time

def parsed_to_date(parsed_date):
    dt = parsed_date.split('/')
    dt = [i if len(i)!=1 else '0'+i for i in dt]
    return '20' + dt[2] + '-' + dt[0] + '-' + dt[1]

def datetime_to_str(dt):
    date = [str(dt.month), str(dt.day), str(dt.year)]
    date = [i if len(i) != 1 else '0' + i for i in date]
    date = date[2] + '-' + date[0] + '-' + date[1]
    return date

def align_daily(data_dict, strike_df):
    data_align = {}
    for idx, row in strike_df.iterrows():
        date = parsed_to_date(row['parsed_date'])
        date_formatted = datetime.datetime.strptime(date, "%Y-%m-%d").date()
        date_prior = datetime_to_str(date_formatted - pd.Timedelta('1 Day'))

        new_id = row['new_id']
        if type(data_dict[new_id].index) != pd.core.indexes.datetimes.DatetimeIndex:
            data_dict[new_id].index = pd.to_datetime(data_dict[new_id].index)

        before = data_dict[new_id].loc[:date_prior]
        after = data_dict[new_id].loc[date:]
        before.index = range(-len(before), 0)
        after.index = range(0, len(after))
        data_align[new_id] = before.append(after)
    return data_align

def number_of_true_rows_before_false(true_false_df):
    temp = true_false_df.copy()
    for col in temp:
        false_levels = temp[col][temp[col] == False].index
        if len(false_levels) == 0:
            continue
        else:
            temp[col].loc[false_levels[0] : ] = False
    return temp